﻿using aier.dataaccess.dapper;
using aier.dataaccess.model;
using aier.xrm.wcf;
using log4net;
using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace aier.business.logic
{
    public class ReservationBll
    {
        public ReservationDal reservationDal { get; set; }

        public LeadDal leadDal { get; set; }
        public ILog log { get; set; }
        public CommonWcf commonWcf { get; set; }

        public Guid InsertReservation(Reservation reservation)
        {
            Entity entity = reservation.AsCrmEntity();
            return commonWcf.CreateEntity(entity);
        }

        /// <summary>
        /// 根据id获取预约记录
        /// </summary>
        /// <param name="reservationid"></param>
        /// <returns></returns>
        public ReservationView FetchReservationById(Guid reservationid)
        {
            try
            {
                ReservationView reservationView = reservationDal.FetchReservationById(reservationid);
                string new_reservationdate = reservationView.new_reservationdate;
                string new_hospitalizeddate = reservationView.new_hospitalizeddate;
                if (reservationView != null)
                {
                    DateTime dateTime = Convert.ToDateTime(new_reservationdate);
                    DateTime dateTime1 = Convert.ToDateTime(new_hospitalizeddate);
                    reservationView.new_reservationdate = dateTime.AddHours(8).ToString();
                    reservationView.new_hospitalizeddate = dateTime1.AddHours(8).ToString();
                    reservationView.source_name = GetSource(reservationView.new_source);
                }
                return reservationView;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取预约来源
        /// </summary>
        /// <returns></returns>
        private string GetSource(int? sourceCode)
        {
            string source = "";
            switch (sourceCode)
            {
                case 1:
                    source = "在线咨询";
                    break;
                case 2:
                    source = "电话咨询";
                    break;
                case 3:
                    source = "社区筛查";
                    break;
                case 4:
                    source = "学术推广";
                    break;
                case 5:
                    source = "会员";
                    break;
                case 6:
                    source = "大客户";
                    break;
                case 7:
                    source = "中小学校园";
                    break;
                case 8:
                    source = "大学校园";
                    break;
                case 9:
                    source = "网络推广";
                    break;
                case 10:
                    source = "主动上门（含口碑）";
                    break;
                case 11:
                    source = "企划管理";
                    break;
                case 99:
                    source = "其他";
                    break;
            }
            return source;
        }

        /// <summary>
        ///  根据开始时间、结束时间、是否到院分页查询预约记录
        /// </summary>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="isHospital"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageResult<ReservationView> QueryReservationByIstohospital(string startdate, string enddate, int isHospital, int pageIndex, int pageSize)
        {
            PageResult<ReservationView> pageResult = new PageResult<ReservationView>();
            IEnumerable<ReservationView> views = reservationDal.QueryReservationByIstohospital(startdate, enddate, isHospital, pageIndex, pageSize);
            if (views != null)
            {
                foreach (ReservationView r in views)
                {
                    r.new_reservationdate = Convert.ToDateTime(r.new_reservationdate).AddHours(8).ToString();
                }
            }
            pageResult.datas = views;
            pageResult.existsnextdata = views.Count() >= pageSize;
            pageResult.total = reservationDal.QueryReservationByIstohospitalCount(startdate, enddate, isHospital);
            return pageResult;
        }


        /// <summary>
        /// 根据潜在顾客ID查询预约记录
        /// 条件：潜在顾客ID
        /// ReservationServiceImpl/QueryReservationByLeadId
        /// </summary>
        /// <param name="leadId"></param>
        /// <returns></returns>
        public ReservationView QueryReservationByLeadId(Guid leadid)
        {
            return reservationDal.QueryReservationByLeadId(leadid);

        }

        /// <summary>
        /// 根据潜在顾客ID查询预约记录
        /// 条件：潜在顾客ID
        /// ReservationServiceImpl/QueryReservationByLeadId
        /// </summary>
        /// <param name="leadId"></param>
        /// <param name="new_insurancetype">医保类型</param>
        /// <returns></returns>
        public ReservationView QueryReservationByLeadId(Guid leadid, bool new_insurancetype)
        {
            return reservationDal.QueryReservationByLeadId(leadid, true);
        }

        public IEnumerable<ReservationView> QueryReservationByLeadIdList(Guid leadid, bool new_insurancetype)
        {
            IEnumerable<ReservationView> views = reservationDal.QueryReservationByLeadIdList(leadid, new_insurancetype);
            if (views != null)
            {
                foreach (ReservationView r in views)
                {
                    r.new_reservationdate = Convert.ToDateTime(r.new_reservationdate).AddHours(8).ToString();
                }
            }
            return views;
        }

        /// <summary>
        /// 根据潜在顾客ID,筛查ID查询预约记录
        /// </summary>
        /// <param name="leadid"></param>
        /// <param name="scid"></param>
        /// <returns></returns>
        public IEnumerable<ReservationView> QueryReservationByLeadIdAndScid(Guid leadid, Guid scid)
        {
            return reservationDal.QueryReservationByLeadIdAndScid(leadid, scid);
        }

        /// <summary>
        /// 创建预约信息
        /// </summary>
        /// <param name="reservationView"></param>
        /// <returns></returns>
        public ResResult CreateReservation(Reservation reservationModel)
        {
            ResResult resResult = null;
            try
            {

                Entity entity = reservationModel.AsCrmEntity();
                
                Guid targetid = Guid.Empty;
                if (reservationModel.userid != Guid.Empty)
                {
                    if (reservationModel.userid != reservationModel.ownerId) {
                        targetid = commonWcf.CreateEntity(entity);
                    }
                    else
                        targetid = commonWcf.CreateEntityProxy(reservationModel.userid, entity);
                }
                else
                {
                    
                    targetid = commonWcf.CreateEntity(entity);
                }
                resResult = new ResResult { ResultState = 1, ResultMes = "Success", Result = targetid };
                return resResult;
            }
            catch (Exception ex)
            {
                log.Error("ReservationDal对象中，CreateReservation方法:" + ex.StackTrace + ex.Message);
                resResult = new ResResult { ResultState = 0, ResultMes = "Fail", Result = ex.Message };
                return resResult;
            }

        }


        /// <summary>
        /// 通过ownerId创建预约信息
        /// </summary>
        /// <param name="reservationView"></param>
        /// <returns></returns>
        public ResResult CreateReservation(Reservation reservationModel, Guid ownerId)
        {
            ResResult resResult = null;
            try
            {
                Entity entity = reservationModel.AsCrmEntity();
                if (reservationModel.new_lead != null)
                {
                    LeadView lead = leadDal.QueryLeadInfoById((Guid)reservationModel.new_lead);

                    if (lead.new_patientsource != null)
                    {
                        entity["new_source"] = new OptionSetValue((int)lead.new_patientsource);
                    }
                    if (lead.new_phone != null)
                    {
                        entity["new_mobile"] = lead.new_phone;
                    }

                    if (lead.new_age != null)
                    {
                        entity["new_age"] = lead.new_age;
                    }
                    if (lead.new_gender != null)
                    {
                        entity["new_gender"] = new OptionSetValue((int)lead.new_gender);
                    }

                    if (lead.new_wechat != null)
                    {
                        entity["new_wechat"] = lead.new_wechat;
                    }
                    if (lead.new_qq != null)
                    {
                        entity["new_qq"] = lead.new_qq;
                    }
                    if (lead.new_insuranceid != null)
                    {
                        entity["new_insuranceid"] = lead.new_insuranceid;
                    }

                    if (lead.new_insurancetype != null)
                    {
                        entity["new_insurancetype"] = new OptionSetValue((int)lead.new_insurancetype);
                    }
                }
                Guid targetid = commonWcf.CreateEntityProxy(ownerId, entity);
                resResult = new ResResult { ResultState = 1, ResultMes = "Success", Result = targetid };
                return resResult;
            }
            catch (Exception ex)
            {
                log.Error("ReservationDal对象中，CreateReservation方法:" + ex.StackTrace + ex.Message);
                resResult = new ResResult { ResultState = 0, ResultMes = "Fail", Result = ex.Message };
                return resResult;
            }

        }

        /// <summary>
        /// 修改预约信息
        /// </summary>
        /// <param name="reservationModel"></param>
        /// <returns></returns>
        public ResResult UpdateReservationDate(Reservation reservationModel)
        {
            ResResult resResult = null;
            try
            {
                Entity entity = reservationModel.AsCrmEntity();
                commonWcf.UpdateEntityById(entity);
                resResult = new ResResult { ResultState = 1, ResultMes = "Success" };
                return resResult;
            }
            catch (Exception ex)
            {
                log.Error("ReservationDal对象中，UpdateReservationDate:" + ex.StackTrace + ex.Message);
                resResult = new ResResult { ResultState = 0, ResultMes = "Fail", Result = ex.Message };
                return resResult;
            }
        }

        public ResResult UpdateReservation(Reservation reservationModel, Guid ownerId)
        {
            ResResult resResult = null;
            try
            {
                Entity entity = reservationModel.AsCrmEntity();
                commonWcf.UpdateEntityProxyById(ownerId, entity);
                resResult = new ResResult { ResultState = 1, ResultMes = "Success" };
                return resResult;
            }
            catch (Exception ex)
            {
                log.Error("ReservationDal对象中，CreateReservation方法:" + ex.StackTrace + ex.Message);
                resResult = new ResResult { ResultState = 0, ResultMes = "Fail", Result = ex.Message };
                return resResult;
            }
        }


        /// <summary>
        /// 查询同一医院,同一科室,同一潜客,同一日期只能有一条预约记录
        /// </summary>
        /// <param name="leadid">潜客ID</param>
        /// <param name="reservationDate">预约日期</param>
        /// <param name="hospitalId">医院ID</param>
        /// <param name="departmentId">科室ID</param>
        /// <returns></returns>
        public int QueryReservationBy(Guid leadid, DateTime startDate, DateTime endDate, Guid hospitalId, Guid departmentId)
        {
            var count = reservationDal.QueryReservationBy(leadid, startDate, endDate, hospitalId, departmentId);
            return count;
        }

        public Guid QueryReservationId(Guid leadid, DateTime startDate, DateTime endDate, Guid hospitalId, Guid departmentId)
        {
            Guid reservationId = reservationDal.QueryReservationId(leadid, startDate, endDate, hospitalId, departmentId);
            return reservationId;
        }

        public Guid CheckExistsReservation(Guid leadid, DateTime startDate, DateTime endDate, Guid hospitalId, Guid departmentId,int item)
        {
            Guid reservationId = reservationDal.CheckExistsReservation(leadid, startDate, endDate, hospitalId, departmentId,item);
            return reservationId;
        }
    }
}
